{% load i18n %}

{% block content %}
<style>
.field-container {
    min-height: 50px;
    padding: 10px;
    border: 1px dashed #ccc;
    margin-bottom: 15px;
    background: #fafafa;
}

div.user-field-item {
    display: inline-flex;
    align-items: center;
    margin: 3px;
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 3px;
    cursor: move;
    position: relative;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    user-select: none;
    margin-bottom: 8px; /* 添加垂直间距 */
    margin-right: 8px;  /* 保持水平间距 */
}

.user-field-item.dragging {
    opacity: 0.5;
    background: #fff3e0;
    border: 2px dashed #ffb74d;
}

.field-container.drag-over {
    background: #e3f2fd;
    border: 2px dashed #2196f3;
}

#orderFields {
    min-height: 100px;
    padding: 15px;
    background: #fafafa;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 8px;  /* 使用gap确保间距一致 */
}

#orderFields .user-field-item {
    background: #fff3e0;
    border-color: #ffb74d;
    cursor: move;
}

.user-field-item .drag-handle {
    cursor: move;
    margin-right: 8px;
    color: #999;
    font-size: 14px;
}

.field-number {
    display: inline-block;
    min-width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    background: #eee;
    border-radius: 10px;
    margin-right: 8px;
    font-size: 12px;
    color: #666;
}

/* .field-type {
    display: none;
} */

.container-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
    display: flex;
    align-items: center;
}

.container-title .badge {
    margin-left: 10px;
    background: #e0e0e0;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
    font-weight: normal;
}

.field-action {
    cursor: pointer;
    margin-left: 8px;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 50%;
    border: 1px solid #ccc;
    font-weight: bold;
    transition: all 0.2s ease;
}

.field-action:hover {
    background: #f0f0f0;
}

.field-action.add {
    color: #4caf50;
    border-color: #4caf50;
}

.field-action.add:hover {
    background: #e8f5e9;
}

.field-action.remove {
    color: #f44336;
    border-color: #f44336;
}

.field-action.remove:hover {
    background: #ffebee;
}

#currentFields .user-field-item {
    background: #e8f5e9;
    border-color: #81c784;
}

#availableFields .user-field-item {
    background: #fff;
    cursor: default;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin: 20px 0 10px;
    padding-bottom: 8px;
    border-bottom: 2px solid #eee;
    color: #333;
}

#orderFields .user-field-item {
    background: #fff3e0;
    border-color: #ffb74d;
    cursor: move;
}

#currentFields {
    background: #fafafa;
    border: none;
}

.alert {
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 4px;
}

.alert-success {
    color: #155724;
    background-color: #d4edda;
    border-color: #c3e6cb;
}

.alert-danger {
    color: #721c24;
    background-color: #f8d7da;
    border-color: #f5c6cb;
}

.alert-dismissible {
    padding-right: 40px;
    position: relative;
}

.alert-dismissible .close {
    position: absolute;
    top: 50%;
    right: 15px;
    transform: translateY(-50%);
    cursor: pointer;
    font-size: 20px;
    font-weight: bold;
    line-height: 1;
    color: inherit;
    text-decoration: none;
    opacity: .5;
}

.alert-dismissible .close:hover {
    opacity: 1;
}

.fields-container {
    display: flex;
    gap: 20px;
    margin: 20px 0;
}

.field-section {
    flex: 1;
    min-width: 0;
    margin-bottom: 20px;
}

.field-container {
    min-height: 50px;
    padding: 10px;
    border: 1px dashed #ccc;
    margin-bottom: 15px;
    background: #fafafa;
    border-radius: 4px;
}

#currentFields {
    background: #f5f5f5;
    border: 1px solid #e0e0e0;
}

#currentFields .user-field-item {
    cursor: default;
    background: #e8f5e9;
    border-color: #81c784;
}

#orderFields .user-field-item {
    background: #fff3e0;
    border-color: #ffb74d;
    cursor: move;
}

#availableFields .user-field-item {
    background: #fff;
}

.user-field-item {
    display: inline-flex;
    align-items: center;
    margin: 3px;
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 3px;
    position: relative;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    user-select: none;
}

#orderFields .user-field-item {
    cursor: move;
}

.field-number {
    display: inline-block;
    min-width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    background: #eee;
    border-radius: 10px;
    margin-right: 8px;
    font-size: 12px;
    color: #666;
}
</style>

<form method="post" id="fieldConfigForm" action="{{ request.path }}">
    {% csrf_token %}
    
    {% if message %}
    <div class="alert alert-{% if success %}success{% else %}danger{% endif %} alert-dismissible">
        {{ message }}
        <a href="#" class="close" onclick="this.parentElement.remove(); return false;">&times;</a>
    </div>
    {% endif %}

    <!-- 当前字段（只读展示） -->
    <div class="field-section">
        <div class="container-title">
            {% trans '当前字段' %}
            <span class="badge margin-r-5" id="currentFieldsCount">{{ current_fields|length }}</span>
            <small class="text-muted">重置时将会恢复这个配置</small>
        </div>
        <div id="currentFields" class="field-container">
            {% for field in current_fields %}
            <span class="user-field-item"
                  data-field-name="{{field.name}}" 
                  data-field-type="{{field.type}}">
                <span class="field-label">{{ field.label }}</span>
            </span>
            {% endfor %}
        </div>
    </div>

    <!-- 拖拽排序区域 -->
    <div class="field-section">
        <div class="container-title">
            {% trans '拖拽排序' %}
            <span class="badge margin-r-5" id="orderFieldsCount">0</span>
            <small class="text-muted">拖拽排序区域内的字段，移动位置进行列表字段排列顺序</small>
        </div>
        <div id="orderFields" class="field-container">
        </div>
    </div>

    <!-- 可用字段 -->
    <div class="field-section">
        <div class="container-title">
            {% trans '可选字段' %}
            <span class="badge margin-r-5" id="availableFieldsCount">0</span>
            <small class="text-muted">可以点击 '+号' 或 '-号' 进行添加或移除字段</small>
        </div>
        <div id="availableFields" class="field-container">
            {% for field in all_fields %}
            <span class="user-field-item"
                  data-field-name="{{field.name}}" 
                  data-field-type="{{field.type}}">
                <span class="field-label">{{ field.label }}</span>
                <span class="field-action add">+</span>
            </span>
            {% endfor %}
        </div>
    </div>

    <div class="footer-actions">
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-sm">{% trans '保存配置' %}</button>
            <button type="button" class="btn btn-default btn-sm" id="resetButton">{% trans '重置排序' %}</button>
            {% if can_reset %}
            <button type="submit" name="resetDefaultButton" class="btn btn-default btn-sm">{% trans '重置默认' %}</button>
            {% endif %}
        </div>
    </div>

    </div>

    <input type="hidden" name="field_order" id="fieldOrder">
</form>

<script>
function initializeFieldConfig() {
    let draggedItem = null;
    const currentFieldsContainer = document.getElementById('currentFields');
    const orderFieldsContainer = document.getElementById('orderFields');
    const availableFieldsContainer = document.getElementById('availableFields');
    const resetButton = document.getElementById('resetButton');

    if (!currentFieldsContainer || !orderFieldsContainer || !availableFieldsContainer) {
        console.error('Required containers not found');
        return;
    }

    // 更新序号和计数
    function updateNumbers() {
        const orderItems = document.querySelectorAll('#orderFields .user-field-item');
        orderItems.forEach((item, index) => {
            const numberSpan = item.querySelector('.field-number');
            if (numberSpan) {
                numberSpan.textContent = (index + 1).toString();
            }
        });

        document.getElementById('orderFieldsCount').textContent = orderItems.length;
        document.getElementById('availableFieldsCount').textContent = 
            document.querySelectorAll('#availableFields .user-field-item').length;
    }

    // 更新可用字段的按钮状态
    function updateAvailableFields() {
        const orderFieldNames = Array.from(document.querySelectorAll('#orderFields .user-field-item'))
            .map(item => item.dataset.fieldName);

        document.querySelectorAll('#availableFields .user-field-item').forEach(item => {
            const fieldName = item.dataset.fieldName;
            const actionBtn = item.querySelector('.field-action');
            
            if (actionBtn) {
                if (orderFieldNames.includes(fieldName)) {
                    actionBtn.classList.remove('add');
                    actionBtn.classList.add('remove');
                    actionBtn.textContent = '-';
                } else {
                    actionBtn.classList.remove('remove');
                    actionBtn.classList.add('add');
                    actionBtn.textContent = '+';
                }
            }
        });
    }

    // 初始化排序区域
    function initOrderFields() {
        orderFieldsContainer.innerHTML = '';
        const currentItems = currentFieldsContainer.querySelectorAll('.user-field-item');
        
        currentItems.forEach((item, index) => {
            const orderItem = document.createElement('div');
            orderItem.className = 'user-field-item';
            orderItem.draggable = true;
            orderItem.dataset.fieldName = item.dataset.fieldName;
            orderItem.dataset.fieldType = item.dataset.fieldType;

            const handleSpan = document.createElement('span');
            handleSpan.className = 'drag-handle';
            handleSpan.textContent = '⋮';

            const numberSpan = document.createElement('span');
            numberSpan.className = 'field-number';
            numberSpan.textContent = (index + 1).toString();
            
            const labelSpan = document.createElement('span');
            labelSpan.className = 'field-label';
            labelSpan.textContent = item.querySelector('.field-label').textContent;

            orderItem.appendChild(handleSpan);
            orderItem.appendChild(numberSpan);
            orderItem.appendChild(labelSpan);

            orderItem.addEventListener('dragstart', handleDragStart);
            orderItem.addEventListener('dragend', handleDragEnd);

            orderFieldsContainer.appendChild(orderItem);
        });
    }

    // 拖拽事件处理
    function handleDragStart(e) {
        draggedItem = this;
        this.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', '');
    }

    function handleDragEnd(e) {
        this.classList.remove('dragging');
        draggedItem = null;
        updateNumbers();
        updateFieldOrder();
        updateAvailableFields();
    }

    // 拖拽区域事件
    orderFieldsContainer.addEventListener('dragover', function(e) {
        e.preventDefault();
        const draggable = document.querySelector('.dragging');
        if (!draggable) return;

        // 获取容器和鼠标的相对位置
        const containerRect = this.getBoundingClientRect();
        const mouseX = e.clientX - containerRect.left;
        const mouseY = e.clientY - containerRect.top;

        // 获取所有非拖动中的字段
        const items = [...this.querySelectorAll('.user-field-item:not(.dragging)')];
        if (items.length === 0) {
            this.appendChild(draggable);
            return;
        }

        // 首先根据垂直位置找到目标行
        let targetRow = [];
        let lastY = -1;
        let currentRow = [];
        
        // 将字段分组到不同的行
        items.forEach(item => {
            const rect = item.getBoundingClientRect();
            const itemY = rect.top - containerRect.top;
            
            if (lastY === -1 || Math.abs(itemY - lastY) < 10) { // 10px 容差
                currentRow.push(item);
            } else {
                if (currentRow.length > 0) {
                    targetRow.push(currentRow);
                }
                currentRow = [item];
            }
            lastY = itemY;
        });
        if (currentRow.length > 0) {
            targetRow.push(currentRow);
        }

        // 找到最近的行
        let closestRow = null;
        let minRowDistance = Infinity;
        
        targetRow.forEach(row => {
            const rowRect = {
                top: row[0].getBoundingClientRect().top - containerRect.top,
                bottom: row[0].getBoundingClientRect().bottom - containerRect.top
            };
            const rowCenter = (rowRect.top + rowRect.bottom) / 2;
            const distance = Math.abs(mouseY - rowCenter);
            
            if (distance < minRowDistance) {
                minRowDistance = distance;
                closestRow = row;
            }
        });

        if (!closestRow) {
            this.appendChild(draggable);
            return;
        }

        // 在目标行中找到最近的字段
        let closestItem = null;
        let minDistance = Infinity;
        let insertAfter = false;

        closestRow.forEach(item => {
            const rect = item.getBoundingClientRect();
            const itemX = rect.left + rect.width / 2 - containerRect.left;
            const distance = Math.abs(mouseX - itemX);

            if (distance < minDistance) {
                minDistance = distance;
                closestItem = item;
                insertAfter = mouseX > itemX;
            }
        });

        // 放置字段
        if (closestItem) {
            if (insertAfter) {
                const nextSibling = closestItem.nextElementSibling;
                if (nextSibling !== draggable) {
                    this.insertBefore(draggable, nextSibling);
                }
            } else {
                if (closestItem !== draggable && closestItem.previousElementSibling !== draggable) {
                    this.insertBefore(draggable, closestItem);
                }
            }
        } else {
            this.appendChild(draggable);
        }
    });

    // 初始化可用字段
    function initAvailableFields() {
        // 获取当前字段名称
        const currentFieldNames = Array.from(currentFieldsContainer.querySelectorAll('.user-field-item'))
            .map(item => item.dataset.fieldName);

        // 获取并排序可用字段
        const availableItems = Array.from(availableFieldsContainer.querySelectorAll('.user-field-item'));
        availableItems.sort((a, b) => {
            const aInCurrent = currentFieldNames.includes(a.dataset.fieldName);
            const bInCurrent = currentFieldNames.includes(b.dataset.fieldName);
            if (aInCurrent === bInCurrent) {
                return a.querySelector('.field-label').textContent.localeCompare(
                    b.querySelector('.field-label').textContent
                );
            }
            return aInCurrent ? -1 : 1;
        });

        // 重新添加排序后的字段
        availableItems.forEach(item => {
            availableFieldsContainer.appendChild(item);
            const actionBtn = item.querySelector('.field-action');
            if (!actionBtn) {
                const btn = document.createElement('span');
                btn.className = 'field-action add';
                btn.textContent = '+';
                item.appendChild(btn);
            }
        });

        // 添加点击事件
        availableFieldsContainer.querySelectorAll('.user-field-item').forEach(item => {
            const actionBtn = item.querySelector('.field-action');
            if (actionBtn) {
                actionBtn.addEventListener('click', function() {
                    const fieldName = item.dataset.fieldName;
                    const orderItem = document.querySelector(`#orderFields .user-field-item[data-field-name="${fieldName}"]`);
                    
                    if (orderItem) {
                        orderItem.remove();
                        actionBtn.textContent = '+';
                        actionBtn.classList.remove('remove');
                        actionBtn.classList.add('add');
                    } else {
                        const newItem = document.createElement('div');
                        newItem.className = 'user-field-item';
                        newItem.draggable = true;
                        newItem.dataset.fieldName = item.dataset.fieldName;
                        newItem.dataset.fieldType = item.dataset.fieldType;

                        const handleSpan = document.createElement('span');
                        handleSpan.className = 'drag-handle';
                        handleSpan.textContent = '⋮';

                        const numberSpan = document.createElement('span');
                        numberSpan.className = 'field-number';
                        numberSpan.textContent = (document.querySelectorAll('#orderFields .user-field-item').length + 1).toString();
                        
                        const labelSpan = document.createElement('span');
                        labelSpan.className = 'field-label';
                        labelSpan.textContent = item.querySelector('.field-label').textContent;

                        newItem.appendChild(handleSpan);
                        newItem.appendChild(numberSpan);
                        newItem.appendChild(labelSpan);

                        newItem.addEventListener('dragstart', handleDragStart);
                        newItem.addEventListener('dragend', handleDragEnd);

                        orderFieldsContainer.appendChild(newItem);
                        actionBtn.textContent = '-';
                        actionBtn.classList.remove('add');
                        actionBtn.classList.add('remove');
                    }
                    
                    updateNumbers();
                    updateFieldOrder();
                });
            }
        });

        updateAvailableFields();
    }

    // 更新字段顺序
    function updateFieldOrder() {
        const orderFields = document.querySelectorAll('#orderFields .user-field-item');
        const fieldOrder = Array.from(orderFields).map(item => item.dataset.fieldName);
        document.getElementById('fieldOrder').value = JSON.stringify(fieldOrder);
    }

    // 初始化
    initOrderFields();
    initAvailableFields();
    updateNumbers();
    updateFieldOrder();

    // 重置按钮
    if (resetButton) {
        resetButton.addEventListener('click', function() {
            initOrderFields();
            updateNumbers();
            updateFieldOrder();
            updateAvailableFields();
        });
    }

    // 表单提交验证
    document.getElementById('fieldConfigForm').addEventListener('submit', function(e) {
        updateFieldOrder();
        if (!document.getElementById('fieldOrder').value) {
            e.preventDefault();
            const alert = document.createElement('div');
            alert.className = 'alert alert-danger alert-dismissible';
            alert.innerHTML = '请至少选择一个字段' + 
                '<a href="#" class="close" onclick="this.parentElement.remove(); return false;">&times;</a>';
            this.insertBefore(alert, this.firstChild);
            return false;
        }
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', initializeFieldConfig);

// htmx 请求完成后重新初始化
document.addEventListener('htmx:afterSwap', function(event) {
    if (event.detail.target.id === 'drawer-content') {
        setTimeout(initializeFieldConfig, 0);
    }
});
</script>
{% endblock %}